#include"packag.h"
#include<QString>
#include <QDebug>
/**
 * @msg: 小车行动封装 封装 命令数据到帧中。 帧由该函数开辟new 空间，出来需要外部释放。
 * @param {activate_car} data:数据结构体
 * @param {char} * & 封装之后的命令。
 * @return {*} 成功返回true 失败返回false
 */
bool packCmdData(const struct activate_car data, char *&COM)
{
    int size = sizeof(struct activate_car)+sizeof(int)+sizeof(long long)+sizeof(char);
    COM = new char[size];
    if(nullptr == COM)
    {
        return false;
    }
    memset((void *)COM,0,size);

    //将头存入
    char *p = COM;
    int top = COM_TOP;
    memcpy((void*)COM,(void*)&top,4);
    COM += 4;

    //存入 数据的大小
    long long data_size = sizeof(struct activate_car);
    memcpy((void*)COM,(void*)&data_size,8);
    COM += 8;

    char c = CAR_BEHAVIOR;
    memcpy((void*)COM,(void*)&c,1);
    COM += 1;

    struct activate_car DATA = data;
    memcpy((void*)COM,(void*)&DATA,sizeof(struct activate_car));

    COM = p;

    return true;
}

/**
 * @msg:喇叭命令封装
 * @param {trumpet} data
 * @param {char} *
 * @return {*}
 */
bool packCmdData(const struct trumpet data, char *&COM)
{
    int size = sizeof(struct trumpet)+sizeof(int)+sizeof(long long)+sizeof(char);
    COM = new char[size];
    if(nullptr == COM)
    {
        return false;
    }
    memset((void *)COM,0,size);

    char *p = COM;

    int top = COM_TOP;
    memcpy((void*)COM,(void*)&top,4);
    COM += 4;

    long long data_size = sizeof(struct trumpet);
    memcpy((void*)COM,(void*)&data_size,8);
    COM += 8;

    char c = TRUMPET;
    memcpy((void*)COM,(void*)&c,1);
    COM += 1;

    struct trumpet DATA = data;
    memcpy((void*)COM,(void*)&DATA,sizeof(struct trumpet));

    COM = p;
    return true;
}

/**
 * @msg: 解析命令头
 * @param {activate_car} &data 保存解析后的数据
 * @param {char} *COM 传指令
 * @return {*}成功返回 true，失败返回false
 */
bool unPackCmdData(struct head &data,const char *COM)
{
    if(nullptr == COM)
    {
        return false;
    }
    char p[13];
    memcpy(p,COM,13);
    data.data_type = *(int *)COM;
    data.size = *(long long *)(COM+4);
    data.cmd_type = *(char *)(COM+12);
    return true;
}

/**
 * @msg:解析小车的环境信息
 * @param {car_behavior} &data
 * @param {char} *COM
 * @return {*}
 */
bool unPackCmdData(struct car_info &data, const char *COM)
{
    if(nullptr == COM)
    {
        return false;
    }
    struct car_info *tmp = (struct car_info *)(COM + 13);
    data.temp = tmp->temp;
    data.hum = tmp->hum;
    data.noise = tmp->noise;
    data.barrier = tmp->barrier;
    data.speed = tmp->speed;
    //data = *tmp;
    return true;
}

/**
 * @msg:摄像头数据解析
 * @param {trumpet} data
 * @param {char} *
 * @return {*}
 */
bool unpackCmdData(char *&p,const char *COM)
{
    if(nullptr == COM)
    {
        return false;
    }

    struct head top;
    unPackCmdData(top,COM);
    p = new char[top.size];
    memcpy(p,COM+13,top.size);

    return true;
}
